package org.akomantoso.core.data;

import java.io.IOException;

import org.akomantoso.core.data.type.TextualMods;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.Output;

/**
 * 
 * The element textualMod is a metadata element specifying an (active or passive) textual modification for the document.
 * 
 * <pre>
 * 	<xsd:element name="textualMod">
 * 		<xsd:complexType>
 * 			<xsd:complexContent>
 * 				<xsd:extension base="modificationType">
 * 					<xsd:sequence>
 * 						<xsd:element ref="old" minOccurs="0" maxOccurs="1" />
 * 						<xsd:element ref="new" minOccurs="0" maxOccurs="1" />
 * 					</xsd:sequence>
 * 					<xsd:attribute name="type" type="TextualMods" use="required" />
 * 				</xsd:extension>
 * 			</xsd:complexContent>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * @since http://www.akomantoso.org/1.0
 */
public final class TextualMod extends ModificationType implements AmendmentsElement {

	public static final String ELEMENT = "textualMod";
	
	public static final String ATTRIBUTE_TYPE = "type";
	
	private TextualMods _type;

	private Old _old;
	
	private New _new;
	
	public TextualMods getType() {
		return _type;
	}

	public void setType(TextualMods type) {
		_type = type;
	}
	
	/**
	 * @see org.akomantoso.core.data.ModificationType#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		out.writeAttribute(ATTRIBUTE_TYPE, _type.name());
		super.writeExternal(out);
		
		if (_old != null) {
			_old.writeExternal(out);
		}
		
		if (_new != null) {
			_new.writeExternal(out);
		}
		
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.data.ModificationType#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		_type = TextualMods.checkValueOf(in.readAttribute(ATTRIBUTE_TYPE));
		super.readExternal(in);
		if (Old.ELEMENT == in.getLocalName()) {
			_old = new Old();
			_old.readExternal(in);
			in.readNextStartOrEndElement();
		}
		if (New.ELEMENT == in.getLocalName()) {
			_new = new New();
			_new.readExternal(in);
			in.readNextStartOrEndElement();
		}
	}
	
}